<template>
	<div class="py-20px px-30px bg-#fff">
		<!-- v-loading="!isFinish" -->
		<div class="min-h-600px" v-loading="loading">
			<!-- 基本信息与动态表单 -->
			<el-form ref="form" :model="entity" :rules="rules" :disabled="params.type == 'info'" label-width="180px"
				:validate-on-rule-change="false">
				<!-- 经销商基本信息 -->
				<el-row :gutter="30" class="flex flex-wrap">
					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="资料类型" prop="dataaudit.dataCategory">
							<el-select class="w-full" disabled filterable v-model="entity.dataaudit.dataCategory" placeholder="请选择">
								<el-option v-for="item in dataTypeList" :key="item.id" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="新车车架号" prop="dataaudit.vinNumber">
							<el-input disabled :maxlength="17" v-model="entity.dataaudit.vinNumber" placeholder="请输入新车车架号"
								clearable />
						</el-form-item>
					</el-col>
					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="4S店所在省份" prop="dataaudit.province">
							<el-input disabled v-model="entity.dataaudit.province" placeholder="请输入" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="4S店所在城市" prop="dataaudit.city">
							<el-input disabled v-model="entity.dataaudit.city" placeholder="请输入" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="4S店名称">
							<el-input v-model="entity.dataaudit.ownerName" disabled />
						</el-form-item>
					</el-col>
					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="ERP编码">
							<el-input v-model="entity.dataaudit.erpCode" disabled />
						</el-form-item>
					</el-col>

					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="本店经营品牌">
							<el-input v-model="entity.dataaudit.manufactureName" disabled />
						</el-form-item>
					</el-col>
					<el-col :lg="8" :md="12" :sm="24">
						<el-form-item label="所属大区">
							<el-input v-model="entity.dataaudit.region" disabled />
						</el-form-item>
					</el-col>
					<template>
						<el-col :lg="8" :md="12" :sm="24">
							<el-form-item label="审核编号">
								<el-input disabled v-model="entity.dataaudit.auditCode" />
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :sm="24">
							<el-form-item label="状态">
								<el-tag v-if="entity.status == 1">待兑现</el-tag>
								<el-tag type="warning" v-if="entity.status == 2">待上传凭证</el-tag>
								<el-tag type="info" v-if="entity.status == 3">待审核</el-tag>
								<el-tag type="danger" v-if="entity.status == 4">驳回待提交</el-tag>
								<el-tag type="success" v-if="entity.status == 5">审核通过</el-tag>
								<el-tag type="danger" v-if="entity.status == 6">已作废</el-tag>
							</el-form-item>
						</el-col>
					</template>
				</el-row>

				<div class="mt-20px">
					<div>
						<div class="text-16px font-bold">车主信息</div>
						<el-divider></el-divider>
					</div>
					<el-row :gutter="30" class="flex flex-wrap mt-30px mb-30px">
						<el-col :lg="11" :md="24">
							<el-row :gutter="30" class="flex flex-wrap">
								<el-col :span="11" :offset="1">
									<el-form-item required prop="certificateUrl" class="text-center leftUpload" label-width="0px">
										<UploadImageOne1 v-model="entity.certificateUrl" :dialogWidth="'700px'" :viewers="allImages"
											:preview="true" :disabled="entity.status != 2">
										</UploadImageOne1>
										<div><span class="text-#F80D0D mr-5px">*</span> 车主身份证</div>
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
						<el-col :lg="13" :md="24">
							<el-row :gutter="10" class="flex flex-wrap">
								<el-col :md="12" :sm="24">
									<el-form-item label="车主姓名">
										<el-input disabled v-model="entity.dataaudit.carOwnerName" />
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="身份证号码">
										<el-input disabled v-model="entity.dataaudit.carOwnerIdNum" />
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="新车车型">
										<el-input disabled v-model="entity.dataaudit.newVehicleType" />
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
					</el-row>
				</div>

				<div class="mt-20px">
					<div>
						<div class="text-16px font-bold">主机厂兑现信息</div>
						<el-divider></el-divider>
					</div>
					<el-row :gutter="30" class="flex flex-wrap mt-30px mb-30px">
						<el-col :lg="11" :md="24">
							<el-row :gutter="30" class="flex flex-wrap">

							</el-row>
						</el-col>
						<el-col :lg="13" :md="24">
							<el-row :gutter="10" class="flex flex-wrap">
								<el-col :md="12" :sm="24">
									<el-form-item label="兑现日期">
										<el-input disabled :value="removeTimeFromDate(entity.exchangeTime)" />
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="兑现金额">
										<el-input disabled v-model="entity.exchangeAmount" />
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="兑现状态">
										<el-tag v-if="entity.exchageStatus == 1">未兑现</el-tag>
										<el-tag v-if="entity.exchageStatus == 2">已兑现</el-tag>
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24" v-if="removeTimeFromDate(entity.feedbackDeadlineTime)">
									<el-form-item label="反馈截止时间">
										<el-input disabled :value="removeTimeFromDate(entity.feedbackDeadlineTime)" />
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
					</el-row>
				</div>

				<div class="mt-20px" v-if="[2, 3, 4, 5].includes(entity.status) || entity.voucherUrls">
					<div>
						<div class="text-16px font-bold">兑现凭证</div>
						<el-divider></el-divider>
					</div>
					<el-row :gutter="30" class="flex flex-wrap mt-30px mb-30px">
						<el-col :lg="11" :md="24">
							<el-row :gutter="30" class="flex flex-wrap">
								<el-col :span="11" :offset="1">
									<el-form-item label="" prop="voucherUrls" class="text-center leftUpload" label-width="0px">
										<UploadImageMore1 v-model="entity.voucherUrls" :dialogWidth="'700px'" :limit="10"
											:showMaxNum="false" :viewers="allImages" :preview="true" :disabled="entity.status != 2">
										</UploadImageMore1>
										<div><span class="text-#F80D0D mr-5px">*</span> 打款凭证 (最少上传1张)</div>
									</el-form-item>
								</el-col>
								<el-col :span="11" :offset="1">
									<el-form-item label="" class="text-center leftUpload" label-width="0px">
										<UploadImageMore1 v-model="entity.otherUrls" :dialogWidth="'700px'" :viewers="allImages"
											:preview="true" :limit="10" :showMaxNum="false" :disabled="entity.status != 2">
										</UploadImageMore1>
										<div>其他 (最多上传10张)</div>
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
						<el-col :lg="13" :md="24">
							<el-row :gutter="10" class="flex flex-wrap">
								<el-col :md="12" :sm="24">
									<el-form-item label="打款日期" prop="makePaymentTime">
										<!-- <el-date-picker v-model="entity.makePaymentTime" :disabled="![2, 4].includes(entity.status)"
											value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" type="datetime" placeholder="选择打款时间"
											align="right">
										</el-date-picker> -->
										<div v-if="![2, 4].includes(entity.status)">
											<el-input placeholder="请选择日期" disabled
												:value="entity.makePaymentTime ? entity.makePaymentTime.split(' ')[0] : ''">
												<i slot="prefix" class="el-input__icon el-icon-date"></i>
											</el-input>
										</div>
										<el-date-picker v-else v-model="entity.makePaymentTime" value-format="yyyy-MM-dd"
											style="width: 100%;" @change="makePaymentTimeChange" type="date" placeholder="选择打款时间"
											align="right">
										</el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="打款金额" prop="makePaymentAmount">
										<el-input-number class="makePaymentAmount" v-model="entity.makePaymentAmount" :min="0"
											:disabled="![2, 4].includes(entity.status)" style="width: 100%;"
											controls-position="right"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="打款方式" prop="paymentType">
										<el-select class="w-full" v-model="entity.paymentType" :disabled="![2, 4].includes(entity.status)">
											<el-option label="银行转账" :value="1"></el-option>
											<el-option label="抵扣车款" :value="2"></el-option>
											<el-option label="其他" :value="3"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="最后一次凭证提交时间">
										<el-input disabled :value="entity.lastVoucherTime || '--'" />
									</el-form-item>
								</el-col>
								<el-col :md="12" :sm="24">
									<el-form-item label="备注">
										<el-input type="textarea"  :maxlength="200"  placeholder="请输入" :rows="4" :disabled="![2, 4].includes(entity.status)"
											v-model="entity.uploadRemark" />
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
					</el-row>
				</div>
				<div class="mt-20px" v-if="entity.status == 4 || entity.additionalUrls">
					<div>
						<div class="text-16px font-bold">补充资料</div>
						<el-divider></el-divider>
					</div>
					<el-row :gutter="30" class="flex flex-wrap mt-30px mb-30px">
						<el-col :lg="11" :md="24">
							<el-row :gutter="30" class="flex flex-wrap">
								<el-col :lg="24" :md="12" :sm="24">
									<el-form-item label-width="0px" class="leftUpload">
										<div v-if="entity.additionalUrls || params.type == 'info'">
											<UploadImageMore1 v-model="entity.additionalUrls" :dialogWidth="'700px'" :viewers="allImages"
												:showTip="false" :preview="true" :disabled="true">
											</UploadImageMore1>
										</div>
										<div v-if="entity.status == 4 && params.type != 'info'">
											<UploadImageMore1 :showTip="false" :viewers="allImages" :dialogWidth="'700px'" :preview="true"
												:limit="12" v-model="additionalUrls" :disabled="entity.status != 4">
											</UploadImageMore1>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
						<el-col :lg="13" :md="24">
							<el-row :gutter="10" class="flex flex-wrap">
								<el-col :lg="24" :md="12" :sm="24">
									<el-form-item label="补充说明">
										<el-input type="textarea" :disabled="entity.status != 4 && params.type == 'info'"
											v-model="entity.additional" :rows="6" placeholder="请输入内容">
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
					</el-row>
				</div>
			</el-form>

			<!-- 审核流程信息 -->
			<div class="mt-20px" v-if="[3, 4, 5].includes(entity.status) || entity.logList">
				<div class="">
					<div class="text-16px font-bold">审核记录</div>
					<el-divider></el-divider>
				</div>
				<div class="mt-30px mb-60px">
					<el-table :data="entity.logList" border style="width: 100%">
						<el-table-column label="审核状态" width="180" align="center">
							<template #default="{ row }">
								<div>
									{{ row.auditStatusStr }}
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="operator" label="处理人" width="180" align="center">
						</el-table-column>
						<el-table-column prop="operateTime" label="处理时间" width="180" align="center">
						</el-table-column>
						<el-table-column prop="auditResult" label="审核结果" width="180" align="center">
							<template #default="{ row }">
								<el-tag type="success" v-if="row.auditResult === 1">
									{{ row.auditResultStr }}
								</el-tag>
								<!-- <el-tag type="warning" v-else-if="row.auditResult === 2">
									驳回
								</el-tag> -->
								<el-tag type="danger" v-else-if="row.auditResult === 2">
									{{ row.auditResultStr }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="审核意见" align="center">
							<template #default="{ row }">
								<div>{{ row.auditOpinion || "--" }}</div>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<!-- 审核信息 -->
			<!-- <div class="mt-20px" v-if="entity.status == 3 && params.type != 'info'">
				<div class="">
					<div class="text-16px font-bold">审核信息</div>
					<el-divider></el-divider>
				</div>
				<div class="mt-30px mb-60px">
					<el-form ref="auditForm" :model="auditForm" label-width="140px" :validate-on-rule-change="false">
						<el-form-item label="审核结果" prop="auditResult" :rules="[
							{
								required: true,
								message: '请选择审核结果',
								trigger: ['change', 'blur'],
							},
						]">
							<el-radio-group v-model="auditForm.auditResult">
								<el-radio :label="1">通过</el-radio>
								<el-radio :label="2">驳回</el-radio>
							</el-radio-group>
						</el-form-item>

						<el-form-item label="审核意见" prop="auditOpinion" :rules="[
							{
								required: true,
								message: '请输入审核意见',
								trigger: 'blur',
							},
						]
							">
							<el-input type="textarea" :maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 8 }"
								v-model="auditForm.auditOpinion" placeholder="请输入审核意见" clearable />
						</el-form-item>
					</el-form>
				</div>
			</div> -->

			<div class="mt-20px flex justify-end">
				<el-button @click="handleGoBack">返回</el-button>
				<el-button :loading="auditLoading" v-if="params.type != 'info'" type="primary" @click="handleAudit">提交
				</el-button>
			</div>
		</div>
	</div>
</template>

<script>
import {
	dataTypeList,
} from "@/api/business";
// import FileUpload from "./components/file-upload.vue";

import {
	getvdataaudiexchangeById,
	examine,//审核
	uploadVoucher,//上传凭证
	againUploadVoucher,//重新上传凭证
} from "@/api/exchangeAndRedemption/index"

export default {
	components: {
		// FileUpload
	},
	data() {
		return {
			loading: true,
			// 页面参数
			params: {},
			typeCategory: "",
			auditForm: {
				id: "",
				auditResult: "",//审核结果
				auditOpinion: "",//审核意见
			},
			// 表单数据
			entity: {
				// 日志
				auditLog: [],
				// 基本信息
				dataaudit: {},
				// 附件信息
				dtoVehicleDataauditAnnexModel: {},
			},
			// 审核状态列表
			auditStatusList: [],
			//资料类型
			dataTypeList: [
				{
					label: "换购",
					value: -1
				},
				{
					label: "增购",
					value: -2
				}, {
					label: "报废",
					value: -3
				}
			],
			auditLoading: false,
			rules: {
				certificateUrl: [
					{ required: true, message: '请上传车主身份证', trigger: 'change' },
				],
				voucherUrls: [
					{ required: true, message: '请上传打款凭证', trigger: 'change' },
				],
				makePaymentTime: [
					{ required: true, message: '请选择打款日期', trigger: 'change' },
				],
				makePaymentAmount: [
					{ required: true, message: '请填写打款金额', trigger: 'change' },
				],
				paymentType: [
					{ required: true, message: '请选择打款方式', trigger: 'change' },
				],
			},
			additionalUrls: null,
			allImages: [],//页面所有图片
			examineObj: {
				time1: "",
				content1: "",
				time2: "",
				content2: "",
			}
		};
	},
	computed: {

	},
	watch: {
		$route: {
			handler(newVal) {
				const query = newVal.query;
				this.params = {
					...query,
					type: query.type || "add",
				};
			},
			immediate: true,
			deep: true,
		},
		additionalUrls: {
			handler() {
				this.allImages = [];
				let arr = ['certificateUrl', 'voucherUrls', 'otherUrls', 'additionalUrls']
				for (let i = 0; i < arr.length; i++) {
					console.log(this.entity[arr[i]]);

					if (this.entity[arr[i]]) {
						this.allImages = this.allImages.concat(this.entity[arr[i]].split(','))
					}
				}
				console.log(this.additionalUrls);

				if (this.additionalUrls) {
					this.allImages = this.allImages.concat(this.additionalUrls.split(","))
				}
			},
			deep: true,
		},
		entity: {
			handler() {
				this.allImages = [];
				let arr = ['certificateUrl', 'voucherUrls', 'otherUrls', 'additionalUrls']
				for (let i = 0; i < arr.length; i++) {
					console.log(this.entity[arr[i]]);

					if (this.entity[arr[i]]) {
						this.allImages = this.allImages.concat(this.entity[arr[i]].split(','))
					}
				}
				console.log(this.additionalUrls);

				if (this.additionalUrls) {
					this.allImages = this.allImages.concat(this.additionalUrls.split(","))
				}
			},
			deep: true,
		}
	},
	beforeRouteEnter(to, from, next) {
		console.log("to", to);
		console.log(from);
		const query = to.query;
		switch (query.type) {
			case "info":
				to.meta.title = "置换兑换详情";
				break;
			case "upload":
				to.meta.title = "置换兑换上传凭证";
				break;
			case "reupload":
				to.meta.title = "置换兑换重新上传凭证";
				break;
			case "examine":
				to.meta.title = "置换兑换审核";
				break;
			default:
				to.meta.title = "";
		}
		next();
	},
	async created() {
		this.getById(this.$route.query.id);
	},
	methods: {
		//查询字典
		async getData(code) {
			try {
				const res = await getData(code);
				console.log(res);
				return res.data.dictValue;
			} catch (e) { }
		},
		makePaymentTimeChange(e) {
			console.log(e);
			if (e) {
				this.entity.makePaymentTime = e + " 00:00:00"
			} else {
				this.entity.makePaymentTime = null;
			}
		},
		removeTimeFromDate(dateString) {
			if (!dateString) return null;

			// 使用正则表达式匹配并提取年月日部分
			const match = dateString.match(/^\d{4}-\d{2}-\d{2}/);

			return match ? match[0] : dateString;
		},
		getById(id) {
			getvdataaudiexchangeById(id).then(res => {
				console.log("res===", res);
				this.entity = res.data;
				this.loading = false;
				// if (this.entity.otherUrls) {
				// 	this.entity.otherUrls = "";
				// }
				let arr = ['certificateUrl', 'voucherUrls', 'otherUrls', 'additionalUrls']
				for (let i = 0; i < arr.length; i++) {
					console.log(this.entity[arr[i]]);

					if (this.entity[arr[i]]) {
						this.allImages = this.allImages.concat(this.entity[arr[i]].split(','))
					}
				}
				if (this.additionalUrls) {
					this.allImages = this.allImages.concat(this.additionalUrls.split(","))
				}
				// certificateUrl
				// voucherUrls
				// otherUrls
				// this.additionalUrls
				// additionalUrls
				if (this.params.type == "examine") {
					let exchangeTime = this.entity.exchangeTime;//兑现日期
					let makePaymentTime = this.entity.makePaymentTime;//打款时间
					let lastVoucherTime = this.entity.lastVoucherTime;//最后一次凭证提交时间
					let result = this.compareDateDifference(makePaymentTime, exchangeTime, this.examineObj.time1);
					let result1 = this.compareDateDifference(lastVoucherTime, exchangeTime, this.examineObj.time2);
					console.log("11111", result);

					if (result == 0) {
						if (this.entity.dataaudit.manufactureName == "奇瑞") {
							this.auditForm.auditOpinion += `${this.examineObj.content1}`;
						}
					}
					if (result1 == 0) {
						if (this.entity.dataaudit.manufactureName == "星途") {
							this.auditForm.auditOpinion += `${this.examineObj.content2}`;
						}
					}
				}
			})
		},
		//判断时间
		compareDateDifference(startDateStr, endDateStr, n) {

			// 将时间字符串转换为 Date 对象
			const startDate = new Date(startDateStr);
			const endDate = new Date(endDateStr);

			// 计算两个时间戳的差值（单位：毫秒）
			const timeDifference = endDate - startDate;

			// 将差值转换为天数
			let daysDifference = Math.abs(timeDifference) / (1000 * 60 * 60 * 24);
			if (timeDifference < 0) {
				daysDifference = -daysDifference;
			}
			// 判断差值是否大于或小于 n 天
			if (daysDifference > n) {
				return 0;
			} else if (daysDifference < n) {
				return 1;
			} else {
				return 2;
			}
		},
		/**
		 * 提交表单
		 * @param
		 */
		handleAudit() {
			if (this.entity.status == 2) {//待上传凭证
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.auditLoading = true;
						uploadVoucher({
							id: this.params.id,
							certificateUrl: this.entity.certificateUrl,
							voucherUrls: this.entity.voucherUrls,
							otherUrls: this.entity.otherUrls,
							makePaymentTime: this.entity.makePaymentTime,
							makePaymentAmount: this.entity.makePaymentAmount,
							paymentType: this.entity.paymentType,
							uploadRemark:this.entity.uploadRemark,
						}).then(res => {
							this.$modal.msgSuccess("上传凭证成功");
							this.auditLoading = false;
							this.$mitt.emit("update-exchangeAndRedemption");
							setTimeout(() => {
								this.handleGoBack();
							}, 500);
						}).catch((err) => {
							this.auditLoading = false;
						})

					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
			// if (this.entity.status == 3) {//审核
			// 	this.$refs['auditForm'].validate((valid) => {
			// 		if (valid) {
			// 			this.auditLoading = true;
			// 			this.auditForm.id = this.params.id
			// 			examine({
			// 				...this.auditForm
			// 			}).then(res => {
			// 				this.$modal.msgSuccess("审核成功");
			// 				this.auditLoading = false;
			// 				this.$mitt.emit("update-exchangeAndRedemption");
			// 				setTimeout(() => {
			// 					this.handleGoBack();
			// 				}, 500);
			// 			}).catch(err => {
			// 				this.auditLoading = false;
			// 			})
			// 		}
			// 	});
			// }
			if (this.entity.status == 4) {//重新上传
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.auditLoading = true;
						againUploadVoucher({
							id: this.params.id,
							additionalUrls: this.entity.additionalUrls ?
								this.entity.additionalUrls.split(",").concat(this.additionalUrls?.split(",") || []).join(",")
								: this.additionalUrls,
							additional: this.entity.additional,
							makePaymentTime: this.entity.makePaymentTime,
							makePaymentAmount: this.entity.makePaymentAmount,
							paymentType: this.entity.paymentType,
							uploadRemark:this.entity.uploadRemark,
						}).then(res => {
							this.$modal.msgSuccess("重新上传凭证成功");
							this.auditLoading = false;
							this.$mitt.emit("update-exchangeAndRedemption");
							setTimeout(() => {
								this.handleGoBack();
							}, 500);
						}).catch((err) => {
							this.auditLoading = false;
						})
					}
				});
			}
		},
		handleGoBack() {
			// this.$tab.closeOpenPage();
			this.$router.back();
		},
	},
};
</script>

<style lang="scss" scoped>
.dealer {
	width: 100%;
	margin-bottom: 10px;
}

// ::v-deep .el-form-item__label {
// 	line-height: inherit !important;
// }

::v-deep .leftUpload {
	.el-form-item__content {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}
}

::v-deep .makePaymentAmount {
	.el-input__inner {
		text-align: left;
	}
}

::v-deep .el-form-item {
	margin-bottom: 32px !important;

	.el-textarea__inner {
		color: #333 !important;
	}

	.el-textarea.is-disabled {
		.el-textarea__inner::placeholder {
			color: #333 !important;
		}
	}
}
</style>
